package snsdbook.servlets;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import snsdbook.beans.FileBean;
import util.SQLUtil;

/**
 * Servlet implementation class FilesServlet
 */
public class FilesServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FilesServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	  if (request.getSession().getAttribute("username") == null) {
      // Not logged in yet
      response.sendRedirect("Index");
    } else {
      ArrayList<FileBean> files = new ArrayList<FileBean>();
      String[] ids = SQLUtil.Query(
          "SELECT id_file FROM files WHERE deleted='0' AND username='" +
          request.getSession().getAttribute("username") + "'");
      for (int i = 0; i < ids.length; ++i) {
        files.add(new FileBean(Integer.valueOf(ids[i]), i));
      }
      request.setAttribute("contents", files);
      
      RequestDispatcher view = request.getRequestDispatcher("/Files.jsp");
      view.forward(request, response);
    }
	}

}
